package org.dhbw.jee.web.security.filter;

import java.io.IOException;

import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dhbw.jee.business.db.User;
import org.dhbw.jee.web.beans.LoginController;

@WebFilter(filterName = "AuthFilter", urlPatterns = { "*.xhtml" })
public class AuthFilter implements Filter {

	@Inject
	LoginController controller;

	public AuthFilter() {
		//
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		try {

			HttpServletRequest req = (HttpServletRequest) request;
			HttpServletResponse res = (HttpServletResponse) response;

			String reqURI = req.getRequestURI();

			User user = controller.getUser();
			if (user != null || reqURI.indexOf("/login.xhtml") >= 0 || reqURI.contains("javax.faces.resource"))
				chain.doFilter(request, response);
			else
				res.sendRedirect(req.getContextPath() + "/login.xhtml");
		} catch (Throwable t) {
			t.printStackTrace();
		}
	}

	public void destroy() {
		//
	}

	public void init(FilterConfig arg0) throws ServletException {
		//
	}

}